package com.jiemengshi.server.qiniu;

import com.alibaba.fastjson.JSONObject;
import com.jiemengshi.server.util.StringUtil;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class PutPolicy {
	private String bucketName;
	private String saveKey;
	private long deadline;
	private String callbackUrl;
	private String callbackBody;
	private String mimeLimit;
	
	private static Mac mac;
	String accessKey;
	String secretKey;
	
	public PutPolicy(String bucketName, String accessKey, String secretKey) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException{
		this.bucketName = bucketName;
		this.accessKey = accessKey;
		this.secretKey = secretKey;
		
		if(mac == null){
			byte[] sk = secretKey.getBytes("utf-8");
			SecretKeySpec secretKeySpec = new SecretKeySpec(sk, "HmacSHA1");
			mac = Mac.getInstance("HmacSHA1");
			mac.init(secretKeySpec);
		}
	}

	public String getToken() throws UnsupportedEncodingException {
		deadline = System.currentTimeMillis() / 1000 + 3600;
		
		JSONObject obj = new JSONObject();
		obj.put("scope ", bucketName);
		obj.put("deadline ", deadline);
		obj.put("saveKey ", saveKey);
		
		if(!StringUtil.isEmpty(mimeLimit))
			obj.put("mimeLimit", mimeLimit);
		
		obj.put("callbackUrl ", callbackUrl);
		obj.put("callbackBody ", callbackBody);
		
		String encodedPutPolicy = UrlSafeBase64.encodeToString(obj.toJSONString().replaceAll("\\s*|\t|\r|\n", ""));
		String encodedSign = UrlSafeBase64.encodeToString(mac.doFinal(encodedPutPolicy.getBytes("utf-8")));
		
		return accessKey+":"+encodedSign+":"+encodedPutPolicy;
	}
	
	public String getBucketName() {
		return bucketName;
	}

	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}

	public String getSaveKey() {
		return saveKey;
	}

	public void setSaveKey(String saveKey) {
		this.saveKey = saveKey;
	}

	public String getCallbackUrl() {
		return callbackUrl;
	}

	public void setCallbackUrl(String callbackUrl) {
		this.callbackUrl = callbackUrl;
	}

	public String getCallbackBody() {
		return callbackBody;
	}

	public void setCallbackBody(String callbackBody) {
		this.callbackBody = callbackBody;
	}

	public String getMimeLimit() {
		return mimeLimit;
	}

	public void setMimeLimit(String mimeLimit) {
		this.mimeLimit = mimeLimit;
	}
}
